package com.shujushow.common.security;

import com.shujushow.common.session.ShiroSession;
import com.shujushow.common.util.SerializeUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Component
public class ShiroSessionRepositoryImpl implements SessionRepository {

    private static final Logger log = LoggerFactory.getLogger(ShiroSessionRepositoryImpl.class);

    private static final String ZCM_SESSION_PREFIX = "zcm-session:";

    @Value("${shiro.globalSessionTimeout:86400000}")
    private Long sessionTimeOut;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void saveSession(Session session) {
        if (session == null || session.getId() == null)
            throw new NullPointerException("session is empty");
        try {
            redisTemplate.opsForValue().set(
                    buildRedisSessionKey(session.getId()),
                    SerializeUtils.serialize(session),
                    sessionTimeOut,
                    TimeUnit.SECONDS);
        } catch (Exception exc) {
            log.error("update session[" + session.getId() + "] error", exc);
        }
    }

    @Override
    public void updateSession(Session session) {
        if (session == null || session.getId() == null)
            throw new NullPointerException("session is empty");
        try {
            redisTemplate.boundValueOps(buildRedisSessionKey(session.getId())).set(
                    SerializeUtils.serialize(session),
                    sessionTimeOut,
                    TimeUnit.SECONDS);
        } catch (Exception exc) {
            log.error("update session[" + session.getId() + "] error", exc);
        }
    }

    @Override
    public void refreshSession(Serializable sessionId) {
        redisTemplate.expire(buildRedisSessionKey(sessionId), sessionTimeOut, TimeUnit.SECONDS);
    }

    @Override
    public void deleteSession(Serializable id) {
        if (id == null) {
            throw new NullPointerException("session id is empty");
        }
        try {

            redisTemplate.delete(buildRedisSessionKey(id));

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("delete session error");
        }
    }

    @Override
    public Session getSession(Serializable id) {
        if (id == null)
            throw new NullPointerException("session id is empty");
        Session session = null;
        try {
            String redisSessionKey = buildRedisSessionKey(id);
            String value = redisTemplate.boundValueOps(redisSessionKey).get();
            if (value == null) {
                session = null;
            } else {
                session = SerializeUtils.deserialize(value, ShiroSession.class);
            }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("get session error");
        }
        return session;
    }

    @Override
    public Collection<Session> getAllSessions() {
        System.out.println("get all sessions");
        return null;
    }

    private String buildRedisSessionKey(Serializable sessionId) {
        return ZCM_SESSION_PREFIX + sessionId;
    }

}